# $Id: Stats.pm,v 1.2 2004/04/27 14:26:22 ibo Exp $

package CGI::FOGE2::Stats;
use CGI::FOGE2::Tools;
use CGI::FOGE2::StatsSimple;
use CGI::FOGE2::StatsPiechart;
use CGI::FOGE2::StatsFree;
use CGI::FOGE2::StatsDouble;

use strict;
our @ISA = ();

sub new {
    my $proto = shift;
    my $params = [ @_ ];
    my $class = ref($proto) || $proto;

    my @mandatory_keys = ();
    my $self  =
	{
        # TODO: change the value of answer to use a view
        # Avoid using theform as a global (argument of new() ?)         FIXME
        answer   => theform->{dbAnswer},
        enquiry  => theform->{enquiry},
        relation => undef,
        columns  => undef,
        question => undef,
        types    => [],
        params   => $params,
	};

    bless ($self, $class);
    return $self;
}

sub setrelation {
    my $self = shift;
    my ($relation) = @_;
    $self->{relation} = $relation;
}

sub setcolumns {
    my $self = shift;
    my ($columns) = @_;
    $self->{columns} = $columns;
}

sub setquestion {
    my $self = shift;
    my ($question) = @_;
    $self->{question} = $question;
}

# Args: none
# Returns: number of answers, 
#          number of expressed answers (if multiple answers allowed),
#          the list of answers,
#          the number of time the corresponding answer was expressed.
# All these data are extracted from the DB in order to produce histograms.

sub computedata {
    my $self = shift;

    if (    defined $self->{question}->{ismultiple} 
         && $self->{question}->{ismultiple} ) {
        return compute_multiple_data($self);
    } else {
        return compute_single_data($self);
    }
}

sub compute_multiple_data {
    my $self = shift;

    my $dbh = theform->dbh_r();
    my $col = $self->{columns}[0];
    my $ans = $self->{answer};
    my $rel = $self->{relation};
    my $sql = 'select %s '
        . 'from %s answer, %s section '
        . 'where answer.id = section.id '
        . 'group by %s';
    $sql = sprintf $sql, $col, $ans, $rel, $col;

    my $sth = $dbh->prepare($sql)
        || die sprintf msg->die_cantprep_query, $dbh->errstr;
    $sth->execute()
        || die sprintf msg->die_cantexec_query, $sth->errstr;

    my %histogram;
    my $number = 0;
    my $separator = $self->{question}->{separator};
    my $regexp = quotemeta($separator);
    while (my $row = $sth->fetchrow_arrayref) {
        $number++;
        my @items = split /$regexp/, $row->[0];
        foreach my $item (@items) {
            #print STDERR "compute_multiple_data $item with $regexp\n"; # DEBUG
            next if $item eq '';
            if ( defined $histogram{$item} ) {
                $histogram{$item}++;
            } else {
                $histogram{$item} = 1;
            }
        }
    }
    my $total = 0;
    my (@names, @vals);
    foreach my $item (sort keys %histogram) {
        push @names, $item;
        push @vals, $histogram{$item};
        $total += $histogram{$item};
    }
    return $number, $total, \@names, \@vals;
}

sub compute_single_data {
    my $self = shift;

    my $dbh = theform->dbh_r();
    my $col = $self->{columns}[0];
    my $ans = $self->{answer};
    my $rel = $self->{relation};
    my $sql = 'select %s, count(*) '
        . 'from %s answer, %s section '
        . 'where answer.id = section.id '
        . 'group by %s';
    $sql = sprintf $sql, $col, $ans, $rel, $col;

    my $sth = $dbh->prepare($sql)
        || die sprintf msg->die_cantprep_query, $dbh->errstr;
    $sth->execute()
        || die sprintf msg->die_cantexec_query, $sth->errstr;

    my $total = 0;
    my (@names, @vals);
    while (my $row = $sth->fetchrow_arrayref) {
        push @names, $row->[0];
        push @vals, $row->[1];
        $total += $row->[1];
    }

    return  $total, $total, \@names, \@vals;
}

sub getdata {
    my $self = shift;
    # Args: none
    # Returns: the column data, as is

    my $dbh = theform->dbh_r();
    my $col = $self->{columns}[0];
    my $ans = $self->{answer};
    my $rel = $self->{relation};
    my $sql = 'select %s '
        . 'from %s answer, %s section '
        . 'where answer.id = section.id '
        . '  and section.%s like \'%%_%%\' '
        . 'order by %s';
    $sql = sprintf $sql, $col, $ans, $rel, $col, $col;

    my $sth = $dbh->prepare($sql)
        || die sprintf msg->die_cantprep_query, $dbh->errstr;
    $sth->execute()
        || die sprintf msg->die_cantexec_query, $sth->errstr;

    my @vals;
    while (my $row = $sth->fetchrow_arrayref) {
        push @vals, $row->[0];
    }

    return \@vals;
}

1;
